﻿using CPPEI.ETL.DataServiceInterface;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.ETL.Domain.DataVerification
{
    public class SPDataVerification : IDataVerification, IDataVerificationContext, IParameterize
    {
        public string Condition { get; private set; }
        private SqlConnection _connection;

        private Parameter[] _parameters;
        public Parameter[] Parameters
        {
            get
            {
                return _parameters;
            }
            set
            {
                _parameters = value;
            }
        }

        public SPDataVerification(string condition)
        {
            Condition = condition;
        }

        public bool Verify(Row row)
        {
            bool isPass = false;
            try
            {
                SqlCommand cmd = new SqlCommand(Condition, _connection);
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                SqlParameter result = new SqlParameter("@Result", System.Data.SqlDbType.Bit);
                result.Direction = System.Data.ParameterDirection.Output;
                cmd.Parameters.Add(result);

                for (int index = 0; index < Parameters.Length; index++)
                {
                    cmd.Parameters.Add(new SqlParameter(string.Format("@{0}", Parameters[index].Name), row.Get(Parameters[index].Value)));
                }

                cmd.ExecuteNonQuery();
                isPass = Convert.ToBoolean(result.Value);
            }
            catch(Exception ex)
            {

            }
            return isPass;
        }

        public void Open()
        {
            _connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["etl-db"].ConnectionString);
            try
            {
                _connection.Open();
            }
            catch(Exception ex)
            {
                _connection.Close();
                _connection = null;
            }
        }

        public void Close()
        {
            try
            {
                _connection.Close();
            }
            catch (Exception ex)
            {
                _connection = null;
            }
        }
    }
}
